//
//  KWTTimePickerView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/8/6.
//

#import "KWTTimePickerView.h"
@interface KWTTimePickerView()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic ,strong) UIPickerView *pickview;
@property (nonatomic, copy) void(^completeBlock)(NSString*);

@property (nonatomic, copy) NSString *titleStr;

@property (nonatomic, copy) NSString *timeStr;

@property (nonatomic,assign) NSInteger hourIndex;//小时

@property (nonatomic,assign) NSInteger minuteIndex;//分钟

@property (nonatomic,strong) NSArray *hourDataArr;

@property (nonatomic,strong) NSArray *minuteDataArr;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, copy) NSString *deviceType;
@end
@implementation KWTTimePickerView

- (instancetype)initWithTitle:(NSString*)titleStr deviceType:(NSString*)deviceType CompleteBlock:(void(^)(NSString *))completeBlock
{
    if (self = [super init]) {
        _deviceType = deviceType;
        [self creatData];
        [self setupUI];
        self.completeBlock = completeBlock;
    }
    return self;
}

-(void)creatData
{
    NSMutableArray *hourArrM = [NSMutableArray array];
    NSMutableArray *minuteM = [NSMutableArray array];
    for (int i = 0; i<24; i++) {
        NSString *hour = [NSString stringWithFormat:@"%02d",i];
        [hourArrM addObject:hour];
    }
    for (int i = 0; i<60; i++) {
        NSString *minute = [NSString stringWithFormat:@"%02d",i];
        if ([self.deviceType isEqualToString:K_EC061060D0]) {
            if (i%30==0) {
                [minuteM addObject:minute];
            }
           
        }else{
            [minuteM addObject:minute];
        }
        
    }
    self.hourDataArr = hourArrM.copy;
    self.minuteDataArr = minuteM.copy;
}

-(void)setupUI
{
//    self.doneButtonColor = RGB(247, 133, 51);
    self.frame = CGRectMake(0, 0, kUI_WINDOW_W, kUI_WINDOW_H);
    kWeakSelf;
    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, kUI_WINDOW_H, kUI_WINDOW_W, kScaleW(300))];
    [self addSubview:_bottomView];
    
    UIView *titleView = [[UIView alloc]init];
    titleView.backgroundColor = kCOLOR_HEX(@"f0f0f0");
   
    [_bottomView addSubview:titleView];
    _bottomView.userInteractionEnabled = YES;
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.offset(45);
    }];
    
    self.titleStr = [NSString checkNull: self.titleStr defaultValue: @"请选择".rh_localized];
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [titleView addSubview:sureBtn];
    CGFloat btnWidth = [sureBtn.titleLabel.text getStringWidthFont:sureBtn.titleLabel.font limitHeight:20];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-10);
        make.height.offset(35);
        make.width.offset(btnWidth+15);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"666666") textAligment:NSTextAlignmentCenter];
    titleLab.text = self.titleStr;
    titleLab.numberOfLines = 2;
    [titleView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.bottom.mas_offset(-0);
        make.centerX.mas_offset(0);
        make.width.offset(kUI_WINDOW_W-btnWidth-30);
    }];
    
    //点击背景是否隐藏
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
    [self addGestureRecognizer:tap];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    
    _pickview = [[UIPickerView alloc]init];
    _pickview.backgroundColor = UIColor.whiteColor;
    [_bottomView addSubview:_pickview];
    _pickview.delegate = self;
    _pickview.dataSource = self;
    [_pickview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.equalTo(titleView.mas_bottom);
    }];
    
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        self.timeStr = [NSString stringWithFormat:@"%02ld:%02ld",[self.hourDataArr[weakSelf.hourIndex] integerValue],[self.minuteDataArr[weakSelf.minuteIndex] integerValue]];
        
        NSInteger startTime = [[weakSelf.startTime stringByReplacingOccurrencesOfString:@":" withString:@""]integerValue];
        NSInteger endTime = [[weakSelf.timeStr stringByReplacingOccurrencesOfString:@":" withString:@""]integerValue];
        if (endTime < startTime) {
            [QMUITips showInfo:@"结束时间必须大于开始时间".rh_localized];
            return;
        }
        
        if (weakSelf.completeBlock) {
           
            weakSelf.completeBlock(weakSelf.timeStr?weakSelf.timeStr:@"00:00");
        }
        [weakSelf dismiss];
    }];
    
    
    [self layoutIfNeeded];
}

-(void)setCurrentTime:(NSString*)time
{
    kWeakSelf;
    self.timeStr = time;
    NSString *showTime = [time compare:self.startTime] == NSOrderedAscending?self.startTime:time;
    NSArray *arr = [showTime componentsSeparatedByString:@":"];
    NSInteger hour = [[arr firstObject] integerValue];
    NSInteger minute = [[arr lastObject] integerValue];
    
    [self.hourDataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (hour == [obj integerValue]) {
            weakSelf.hourIndex = idx;
            [weakSelf.pickview selectRow:idx inComponent:0 animated:NO];
        }
    }];
    [self.minuteDataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (minute == [obj integerValue]) {
            weakSelf.minuteIndex = idx;
            [weakSelf.pickview selectRow:idx inComponent:1 animated:NO];
        }
    }];
    
    
   
   
}


#pragma mark - UIPickerViewDelegate,UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.hourDataArr.count;
    }
   
    return self.minuteDataArr.count;
}


- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 52;
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *customLabel = (UILabel *)view;
    if (!customLabel) {
        customLabel = [[UILabel alloc] init];
        customLabel.textAlignment = NSTextAlignmentCenter;
        [customLabel setFont:[UIFont systemFontOfSize: 16]];
        customLabel.textColor = [UIColor blackColor];
    }
   
    if (component == 0) {
        customLabel.text = [NSString stringWithFormat:@"%02ld",[self.hourDataArr[row] integerValue]];
    }else{
        customLabel.text = [NSString stringWithFormat:@"%02ld",[self.minuteDataArr[row] integerValue]];
    }
    
    
    
    return customLabel;
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.hourIndex = row;
    }else{
        self.minuteIndex = row;
    }
    
    
}
#pragma mark - Action
- (void)show {
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:.3 animations:^{
        self.bottomView.y = kUI_WINDOW_H-self.bottomView.height;
        self.backgroundColor = kColorRGBA(0, 0, 0, 0.4);
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:.3 animations:^{
        self.bottomView.y = self.height;
        self.backgroundColor = kColorRGBA(0, 0, 0, 0);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
@end
